<template>
  <div>
    <div class="row">
      <div class="col">
        <el-input placeholder="请输入内容" @change="start" v-model.lazy="like">
          <template #append>
            <el-button @click="start">
              <el-icon>
                <Search />
              </el-icon>
            </el-button>
          </template>
        </el-input>
      </div>
      <div class="col text-right">
        <el-button @click="opened">+创建通知</el-button>
      </div>
    </div>
    <el-table :data="tableData" height="65vh" style="width: 100%" @sort-change="sortchange">
      <el-table-column prop="ID" label="ID"></el-table-column>
      <el-table-column prop="name" label="标题"></el-table-column>
      <el-table-column prop="info" label="备注"></el-table-column>
      <el-table-column
        prop="readnumber"
        :formatter="({ usernotice }) => usernotice.length"
        label="已读人数"
      ></el-table-column>
      <el-table-column
        prop="createdAt"
        sortable="custom"
        :formatter="({ createdAt }) => formatter(createdAt)"
        label="发布时间"
      ></el-table-column>
      <el-table-column label="操作" width="180">
        <template #default="scope">
          <el-button type="danger" @click="del(scope.row.ID)" size="default">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      :="true"
      @current-change="handleCurrentChange"
      :page-size="Number(limit)"
      layout="prev, pager, next"
      :total="count"
    ></el-pagination>
    <el-dialog :title="title" v-model="dialogVisible" width="80%">
      <el-form
        size="default"
        :model="ruleForm"
        :rules="rules"
        ref="ruleForm"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item label="标题">
          <el-input v-model="ruleForm.name"></el-input>
        </el-form-item>
        <el-form-item label="备注">
          <el-input v-model="ruleForm.info"></el-input>
        </el-form-item>
        <el-form-item label="跳转链接">
          <el-input v-model="ruleForm.description"></el-input>
        </el-form-item>
        <el-form-item label="用户">
          <el-radio-group v-model="ruleForm.type">
            <el-radio label="public">所有用户</el-radio>
            <el-radio label="limit">指定人员</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item v-if="ruleForm.type === 'limit'" label="选择人员">
          <el-input placeholder="请输入内容" v-model="users" disabled class="input-with-select">
            <template #append>
              <el-button @click="dialogVisible2 = true">选择用户</el-button>
            </template>
          </el-input>

          <el-dialog
            title="请选择用户"
            v-model="dialogVisible2"
            width="900px"
            close-on-click-modal
            close-on-press-escape
          >
            <User
              :tablekey="['name', 'headportrait']"
              :handleSelectionChange="handleSelectionChange"
              :selectarr="selectarr"
            ></User>
            <template #footer>
              <span class="dialog-footer">
                <el-button @click="dialogVisible2 = false">关闭</el-button>
              </span>
            </template>
          </el-dialog>
        </el-form-item>
        <div class="row">
          <div class="col text-right">
            <el-button @click="dialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="submit">确 定</el-button>
          </div>
        </div>
      </el-form>
    </el-dialog>
  </div>
</template>
<script lang="ts">
import { ElMessage } from "element-plus";
import { toLocaleDateString } from "../../../util/time";
import {
  asyncdelnotice,
  asynccreateorupdatenotice,
  asyncselectnotice,
  IApinotice,
} from "../../../api/index";
import User from "../../../admin/views/User/index.vue";
import Studycodemodel from '../../../mysql_interface/studycodemodel';
import { defineComponent } from 'vue'
type D = {
  dialogVisible: boolean
  activeName: string
  sortable: "DESC" | "ASC" | undefined
  limit: number
  offset: number
  like: string
  title: string
  ID?: number
  context: string
  ruleForm: IApinotice
  rules: object
  dialogVisible2: object
  users: string[]
  tableData: Studycodemodel.Inotice[]
  count: number
  order: keyof Studycodemodel.Inotice
}

export default defineComponent({
  name: "Notice",
  components: {
    User,
  },

  data() {
    return {
      dialogVisible: false,
      activeName: "详情",
      sortable: "DESC",
      limit: 20,
      offset: 0,
      order: "ID",
      like: "",
      title: "添加",
      ID: undefined,
      context: "context",
      ruleForm: Object.assign({}),
      rules: {},
      dialogVisible2: false,
      users: [],
      tableData: [],
      count: 0,
    } as unknown as D
  },
  async mounted() {
    this.start();
  },
  watch: {
    limit() {
      this.start();
    },
    offset() {
      this.start();
    },
    order() {
      this.start();
    },
    sortable() {
      this.start();
    },
    like() {
      this.limit = 20;
      this.offset = 0;
    },
  },
  methods: {
    async start() {
      let { limit, offset, order, sortable, like } = this;
      try {
        let z: [keyof Studycodemodel.Inotice, any] | undefined;
        if (like.value) {
          z = ["name", like];
        }
        const { rows, count } = await asyncselectnotice({
          _limit: limit,
          _offset: offset,
          _order: order,
          _sortable: sortable,
          _like: z,

        });
        this.tableData = rows;
        this.count = count;
      } catch (e: any) {
        ElMessage.error(e);
      }
    },
    handleCurrentChange(val: number) {
      this.offset = this.limit * (val - 1);
    },
    handleSelectionChange(data: Studycodemodel.Iuser[]) {
      this.ruleForm.users = data.map((e) => e.ID) as number[]
      this.users = data.map((e) => e.name) as string[]
    },
    handleClick(row: Studycodemodel.Inotice) {
      this.title = "修改";
      this.ruleForm = JSON.parse(JSON.stringify(row));
      this.dialogVisible = true;
    },
    opened() {
      if (this.dialogVisible) {
        this.dialogVisible = false;
        return;
      }
      this.ruleForm = Object.assign(this.ruleForm, {});
      this.dialogVisible = true;
    },
    sortchange(row: any) {
      const { prop, order } = row;
      if (order == "descending") {
        this.sortable = "DESC";
      } else {
        this.sortable = "ASC";
      }
      this.order = prop;
    },
    formatter(updatedAt: string) {
      return toLocaleDateString(updatedAt);
    },
    del(ID: number) {
      try {
        this.$confirm("是否删除该选项, 是否继续?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        })
          .then(async () => {
            await asyncdelnotice({ ID });
            ElMessage({
              type: "success",
              message: "删除成功!",
            });
            this.start();
          })
          .catch((e: string) => {
            ElMessage({
              message: "删除失败" + e,
              type: "error",
            });
          });
      } catch (e: any) {
        ElMessage({
          type: "info",
          message: "已取消删除",
        });
      }
    },
    async submit() {
      try {
        await asynccreateorupdatenotice(this.ruleForm);
        ElMessage({
          message: "添加成功",
          type: "success",
        });
        this.start();
        this.dialogVisible = false;
      } catch (e: any) {
        ElMessage({
          message: e,
          type: "error",
        });
      }
    },
  },
})
</script>
